<template>
  <div class="bigbox-real">
    <div class="topbox">
      <el-form ref="form" label-position="left" label-width="80px">
        <el-row :gutter="20">
          <el-col :span="5">
            <el-form-item label="用电企业">
              <el-select
                v-model="formdata.orgNo"
                size="small"
                clearable
                filterable
                style="width: 100%"
                @change="gettablist"
              >
                <el-option
                  class="option"
                  v-for="item in conplae"
                  :key="item.orgNo"
                  :label="item.orgName"
                  :value="item.orgNo"
                  suffix-icon="el-icon-date"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="报警等级">
              <el-button-group>
                <el-button
                  v-for="item in levearray"
                  :key="item.name"
                  size="small"
                  :type="alarmLevel == item.leve ? item.type : ' '"
                  @click="checkleve(item)"
                  >{{ item.name }} {{ item.value }}</el-button
                >
              </el-button-group>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="是否确认">
              <el-switch
                v-model="formdata.isProcessed"
                active-color="#1890ff"
                inactive-color="#ccc"
                @change="gettablist"
              >
              </el-switch>
            </el-form-item>
          </el-col>
          <el-col :span="4" style="text-align: right">
            <el-form-item label="">
              <el-button @click="chongzhi" size="small">重 置</el-button>
              <el-button @click="gettablist" size="small" type="primary"
                >查 询</el-button
              >
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div class="bodybox">
      <TopTitle :showexcel="false" @command="command" @shuaxin="gettablist">
        <template #leftother>
          <div class="lefybox">
            <div class="texts">实时报警</div>
            <div>
              <el-button
                @click="checktype({ alarmType: '' })"
                :type="alarmType == '' ? 'primary' : ''"
                size="small"
                >全部</el-button
              >
              <el-button
                size="small"
                @click="checktype(item)"
                v-for="(item, index) in typelist"
                :type="alarmType == item.alarmType ? 'primary' : ''"
                :key="index"
                >{{ item.description }} {{ item.alarmCount }}</el-button
              >
            </div>
          </div>
        </template>
        <template #otherbutton>
          <span class="text">注：近30日内报警</span>
        </template>
      </TopTitle>
      <div class="tablebox">
        <el-table
          v-loading="loading"
          :data="tableData"
          style="width: 100%"
          border
          height="calc(100% - 1px)"
          :size="iissize"
          :header-cell-style="{
            'text-align': 'center',
            background: '#f5f5f5'
          }"
        >
          <template slot="empty">
            <el-empty description="暂无数据"></el-empty>
          </template>
          <el-table-column
            type="index"
            fixed
            align="center"
            label="序号"
            width="50"
          >
          </el-table-column>
          <el-table-column
            width="120"
            align="center"
            prop="eventLevelName"
            label="告警等级"
            fixed
          >
            <template #default="{ row }">
              <span
                class="gaojingdengji"
                :class="{
                  yellow: row.eventLevel == '2',
                  gard: row.eventLevel == '1',
                  red: row.eventLevel == '3',
                   green: row.eventLevel == '0',
                }"
              >
                {{ row.eventLevelName }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="orgName" label="用电企业" width="220" />
          <el-table-column prop="switchRoom" label="区域" width="220" />
          <el-table-column prop="devName" label="设备名称" width="220" />
          <el-table-column
            prop="measureName"
            label="告警信号"
            min-width="150"
          />
          <el-table-column prop="eventDesc" label="告警描述" width="400" />
          <el-table-column
            prop="alarmTime"
            label="告警时间"
            align="center"
            width="200"
          />
          <el-table-column prop="alarmValue" label="告警值" align="right" />
          <el-table-column prop="isReturn" label="复归" align="center">
            <template #default="{ row }">
              <span>{{ row.isReturn ? '是' : '否' }}</span>
            </template>
          </el-table-column>
          <el-table-column
            width="150"
            align="center"
            fixed="right"
            label="操作"
          >
            <template #default="{ row }">
              <el-button type="text" size="small" @click="sure(row)"
                >确认</el-button
              >
              <el-button type="text" size="small" @click="fugui(row)"
                >复归</el-button
              >
              <el-button type="text" size="small" @click="jiankong(row)"
                >监控</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 底部分页 -->
      <div class="fenye">
        <el-pagination
          background
          layout="prev, pager, next"
          :current-page.sync="pageobj._pageNo"
          @current-change="gettablist"
          :total="+totalCount"
        >
        </el-pagination>
      </div>
      <el-dialog :visible.sync="dialogVisible" width="40%" center @close="quxiao">
        <div>
          <div style="font-weight: 600">处理描述</div>
          <div style="margin: 25px 0">
            <el-input type="textarea" :rows="2" v-model="diaval.content">
            </el-input>
          </div>
          <div>确认时间: {{ diaval.processTime }}</div>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button type="primary" size="small" @click="miaoshu">
            确 定
          </el-button>
          <el-button @click="quxiao" size="small">
            取 消
          </el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import dayjs from 'dayjs'
import TopTitle from '@/components/TopTitle/newtitle.vue'
import {
  getalarmCompanyListapi,
  getrealTimeAlarmListapi,
  getfuguiapi,
  getsurebaocunapi,
  getfenzuapi
} from '@/api/realtime'
import request from '@/utils/request'
export default {
  name: 'CallPoliceIndex',
  components: {
    TopTitle
  },
  data() {
    return {
      loading: false,
      formdata: { isProcessed: false, orgNo: '' },
      conplae: [],
      tableData: [],
      pageobj: {
        _pageNo: 0,
        _pageSize: 15
      },
      totalCount: 0,
      iissize: 'medium',
      typelist: [],
      levelist: [],
      alarmLevel: ' ',
      alarmType: '',
      dialogVisible: false,
      diaval: { soeid: '', timeobj: '', textarea: '' },
      levearray:[],
      timer:null
    }
  },

  async mounted() {
    const {
      data: { list }
    } = await getalarmCompanyListapi()
    this.conplae = list
    const {data:{list:array}}=await getfenzuapi()
    this.levelist=array
    this.gettablist()
    this.setInterva()
  },

  methods: {
    async gettablist() {
      this.loading = true
      const {
        data: { list, totalCount, content }
      } = await getrealTimeAlarmListapi({
        _pageNo: this.pageobj._pageNo - 1,
        _pageSize: this.pageobj._pageSize,
        ...this.formdata,
        alarmLevel: this.alarmLevel == ' ' ? '' : this.alarmLevel,
        alarmType: this.alarmType
      })
      this.totalCount = totalCount
      const obj = JSON.parse(content)
      this.typelist = obj.alarmTypeCountList
      const levelItems = this.levelist.map(item => {
        const value = obj.alarmLevelCountMap[item.value]; // 从map中获取数量
        // 根据value匹配对应的type
        const typeMap = {'0': 'success','1': 'info','2': 'warning','3': 'danger'};
        return {
          value: value,
          name: item.text,       // 从list中获取名称
          leve: item.value,      // 对应level值
          type: typeMap[item.value] // 匹配类型
        };
      });
      const total = levelItems.reduce((sum, item) => sum + item.value, 0);
      this.levearray = [
        { value: total, name: '全部', leve: ' ', type: 'primary' },
        ...levelItems.sort((a, b) => b.leve - a.leve) // 按leve降序排列（严重到一般）
      ];
      console.log(this.levearray);
      
      this.tableData = list
      this.loading = false
    },
    // 切换等级
    checkleve(item) {
      this.alarmLevel = item.leve
      this.alarmType = ''
      this.gettablist()
    },
    // 切换类型
    checktype(row) {
      this.alarmType = row.alarmType
      this.gettablist()
    },
    // 复归
    async fugui(row) {
      const res = await getfuguiapi({ soeid: row.soeid })
      this.$message({
        type: res.code == '200' ? 'success' : 'warning',
        message: res.code == '200' ? '复归成功' : res.message
      })
      this.getgaojing()
    },
    // 确认
    sure(row) {
      this.dialogVisible = true
      this.diaval.soeid = row.soeid
      this.diaval.processTime = dayjs().format('YYYY-MM-DD HH:mm:ss')
    },
    async miaoshu() {
      const res = await getsurebaocunapi(this.diaval)
      this.$message({
        type: res.code == '200' ? 'success' : 'warning',
        message: res.code == '200' ? '操作成功' : res.message
      })
      this.getgaojing()
    },
    quxiao(){
      this.dialogVisible = false
      this.diaval={ soeid: '', timeobj: '', textarea: '' }
    },
    // 去监控
    jiankong(val) {
      const routeData = this.$router.resolve({
        path: '/realtimes',
        query: { id: val.devId, name: val.devName }
      })
      window.open(routeData.href, '_blank')
    },
    command(val) {
      this.iissize = val
    },
    chongzhi() {
      this.formdata = { isProcessed: false, orgNo: '' }
      this.alarmLevel = ' '
      this.alarmType = ''
      this.gettablist()
    },
    setInterva() {
      this.timer = setInterval(async () => {
        await this.gettablist()
      }, 60000)
    },
  },
  beforeDestroy() {
    clearInterval(this.timer)
  }
}
</script>
<style lang="scss" scoped>
.bigbox-real {
  height: 100%;
  background-color: #f1f1f1;
  padding: 10px;
  .topbox {
    background-color: #fff;
    padding: 20px;
    height: 80px;
    margin-bottom: 10px;
  }
  .bodybox {
    height: calc(100% - 90px);
    background-color: #fff;
    padding: 20px;
    .lefybox {
      display: flex;
      align-items: center;
      .texts {
        margin-right: 30px;
      }
    }
    .text {
      font-size: 12px;
      color: #ccc;
    }
    .tablebox {
      height: calc(100% - 80px);
      .gaojingdengji {
        width:auto;
        padding: 4px 5px;
        display: inline-block;
        border-radius: 6px;
        color: #fff;
        text-align: center;
      }
      .yellow {
        background: #e6ae2e;
      }
      .red {
        background: #f56c6c;
      }
      .green {
        background: #67c23a;
      }
      .gard{
        background-color: #909399;
      }
    }
    .fenye {
      margin-top: 10px;
      text-align: right;
    }
  }
}
</style>
